package com.rabbiter.oes.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbiter.oes.entity.JudgeQuestion;
import org.apache.ibatis.annotations.*;

import java.util.List;

//判断题

@Mapper
public interface JudgeQuestionMapper extends BaseMapper<JudgeQuestion> {

    /**
     * 根据 paperId 查询判断题（questionType = 3）
     */
    @Select("SELECT * FROM judge_question " +
            "WHERE questionId IN " +
            "(SELECT questionId FROM paper_manage WHERE questionType = 3 AND paperId = #{paperId})")
    List<JudgeQuestion> findByIdAndType(String paperId);

    /**
     * 分页查询所有判断题
     */
    @Select("SELECT * FROM judge_question")
    IPage<JudgeQuestion> findAll(Page page);

    /**
     * 查询最后一条记录的 questionId（返回 JudgeQuestion，但只填充 questionId）
     * 注意：其他字段会是 null，但不影响使用
     */
    @Select("SELECT questionId FROM judge_question ORDER BY questionId DESC LIMIT 1")
    JudgeQuestion findOnlyQuestionId();

    /**
     * 插入判断题（只插入实体类中有的字段）
     */
    @Insert("INSERT INTO judge_question (subject, question, rightAnswer, analysis, score) " +
            "VALUES (#{subject}, #{question}, #{rightAnswer}, #{analysis}, #{score})")
    int add(JudgeQuestion judgeQuestion);

    /**
     * 根据科目随机抽取指定数量的题目ID
     */
    @Select("SELECT questionId FROM judge_question " +
            "WHERE subject = #{subject} " +
            "ORDER BY RAND() DESC " +
            "LIMIT #{pageNo}")
    List<Integer> findBySubject(@Param("subject") String subject, @Param("pageNo") Integer pageNo);

    /**
     * 更新判断题信息（只更新存在的字段）
     */
    @Update("UPDATE judge_question " +
            "SET subject = #{subject}, " +
            "    question = #{question}, " +
            "    rightAnswer = #{rightAnswer}, " +
            "    analysis = #{analysis}, " +
            "    score = #{score} " +
            "WHERE questionId = #{questionId}")
    int edit(JudgeQuestion judgeQuestion);

    @Select("SELECT * FROM judge_question " +
            "WHERE subject = #{subject} " +
            "ORDER BY RAND() LIMIT #{count}")
    List<JudgeQuestion> findRandom(
            @Param("count") Integer count,
            @Param("subject") String subject
    );

    @Select("select * from judge_question where subject=#{subject}")
    List<JudgeQuestion> findSequence(String subject);
    @Select(" SELECT jq.* FROM judge_question jq INNER JOIN paper_manage pm ON jq.questionId = pm.questionId  WHERE pm.PaperId = #{PaperId} AND pm.userId = #{userId} AND pm.questionType = 3 ")
    List<JudgeQuestion> findByExamCodeAndUserId(String PaperId, Long userId);
}
